<template>
  <div class="inspection-details-container">
    <div class="header" header="详情">
      <a-button class="back-button" @click="gotoBack"> 返回 </a-button>
    </div>
    <div class="main" v-loading="pageLoading">
      <!-- 头部流程 -->
      <flowList
        :source="flowSource"
        replaceFields="dealName"
        v-if="flowSource.length > 0 && showFlow == 'true'"
      >
      </flowList>
      <div class="title">报验信息</div>
      <a-collapse v-model="activeKey">
        <a-collapse-panel
          :key="item.id"
          :show-arrow="false"
          v-for="(item, index) in basicData"
        >
          <template slot="header">
            <div @click.stop class="customize-text">
              <div class="cust-collapse-header" style="padding-left: 0">
                ● 工序信息（{{ index + 1 }}）- {{ item.procedureItem }}
              </div>
            </div>
          </template>
          <template slot="extra">
            <div class="customize-extra">
              {{ activeKey.includes(item.id) ? "收起" : "展开" }}
              <div
                class="icon"
                :class="[activeKey.includes(item.id) && 'active']"
              >
                <bj-icon-font
                  type="xl"
                  color="#0068B7"
                  :size="10"
                ></bj-icon-font>
              </div>
            </div>
          </template>
          <a-form-model ref="ruleForm">
            <processesCard
              v-if="item.loaded"
              :operateMode="item.operateMode"
              :forms.sync="item.formList"
              @fileDownload="download($event)"
              @filePreview="viewFile($event)"
            ></processesCard>
          </a-form-model>
        </a-collapse-panel>
      </a-collapse>
      <a-collapse v-model="activeKey2" v-if="showFlow == 'true'">
        <a-collapse-panel key="1" :show-arrow="false">
          <template slot="header">
            <div @click.stop class="customize-text" header="处理记录">
              <div class="cust-collapse-header">
                <div>报验人：{{ resultData.creater }}</div>
                <div>
                  处理状态：
                  <span class="flow" :class="[checkStatusClass(resultData)]">
                    {{ fliterName(resultData) }}
                  </span>
                </div>
              </div>
            </div>
          </template>
          <template slot="extra">
            <div class="customize-extra">
              {{ activeKey2.includes("1") ? "收起" : "展开" }}
              <div class="icon" :class="[activeKey2.includes('1') && 'active']">
                <bj-icon-font
                  type="xl"
                  color="#0068B7"
                  :size="10"
                ></bj-icon-font>
              </div>
            </div>
          </template>
          <div class="approve-record-container">
            <div class="item" v-for="(item, index) in record" :key="index">
              <div class="time-date">{{ item.updateTime }}</div>
              <div class="link-line">
                <div class="content">
                  <div class="dots"></div>
                  <div :class="index != record.length - 1 ? 'lines' : ''"></div>
                </div>
              </div>
              <div class="approve-container">
                <div class="approve-user">
                  <div class="name">{{ item.sysUsername }}</div>
                  <div class="result">{{ item.wfnodename }}</div>
                </div>
                <div class="approve-content" v-if="item.reason">
                  处理意见：{{ item.reason }}
                </div>
                <template v-if="item.operation != '0' && item.operation != '1'">
                  <transition name="slide-fade">
                    <div v-if="approveKey.includes(item.id)">
                      <template v-if="item.formList.length > 0">
                        <div
                          class="approve-collapse"
                          v-for="(v, i) in item.formList"
                          :key="i"
                        >
                          <div class="name">{{ v.elementName }}：</div>
                          <div class="content">
                            <div
                              class="text-container"
                              v-if="
                                v.elementType == '1' ||
                                v.elementType == '2' ||
                                v.elementType == '7'
                              "
                            >
                              {{ v.elementValue }}
                            </div>
                            <bjUploadFile
                              v-if="v.elementType == '3'"
                              v-model="v.fileList"
                              :viewMode="true"
                              @download="download($event)"
                              @preview="viewFile($event)"
                              :replaceFields="{
                                fileName: 'realFileName',
                                fileSize: 'fileSize',
                                fileType: 'fileType',
                                videoSrc: 'fileUrl',
                              }"
                            ></bjUploadFile>
                            <bjUploadImg
                              v-if="v.elementType == '4'"
                              v-model="v.fileList"
                              :viewMode="true"
                              replaceField="imagePath"
                            ></bjUploadImg>
                            <bjUploadFile
                              v-if="v.elementType == '5'"
                              v-model="v.fileList"
                              :viewMode="true"
                              :replaceFields="{
                                fileName: 'realFileName',
                                fileSize: 'fileSize',
                                fileType: 'fileType',
                                videoSrc: 'imagePath',
                              }"
                              type="video"
                            ></bjUploadFile>
                          </div>
                        </div>
                      </template>
                      <div v-else>
                        <a-empty />
                      </div>
                    </div>
                  </transition>
                </template>
                <div
                  class="approve-extra"
                  v-if="item.operation != '0' && item.operation != '1'"
                  @click="putAwayMore(item)"
                >
                  {{ approveKey.includes(item.id) ? "收起" : "更多" }}
                  <div
                    class="icon"
                    :class="[approveKey.includes(item.id) && 'active']"
                  >
                    <bj-icon-font
                      type="xl"
                      color="#0068B7"
                      :size="10"
                    ></bj-icon-font>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </a-collapse-panel>
      </a-collapse>
    </div>
  </div>
</template>

<script>
import flowList from "@/components/flow-list";
import bjUploadFile from "@/components/bj-upload-file";
import bjUploadImg from "@/components/bj-upload-img";
import {
  bYJLDetails,
  getInspectionInit,
  getSelfTestPeople,
} from "@/api/wisdom-beam/quality-app";
import processesCard from "./components/processesCard";
import { downFileByUrl, commonViewFile } from "@/utils";
export default {
  components: {
    flowList,
    bjUploadFile,
    bjUploadImg,
    processesCard,
  },
  data() {
    return {
      pageLoading: false,
      activeKey: [],
      activeKey2: ["1"],
      resultData: {},
      //头部流程
      flowSource: [],
      //处理记录
      approveKey: [],
      record: [],
      //表单
      basicData: [],
      showFlow: "false",
      //自检人
      selfPeopleSelect: [],
    };
  },
  mounted() {
    let { showFlow } = this.$route.query;
    this.showFlow = showFlow;
    this.getPeopleData();
    this.$nextTick(() => {
      this.initPage();
    });
  },
  methods: {
    //查询自检人
    getPeopleData() {
      let { orgCode } = this.$route.query;
      return new Promise((resolve, reject) => {
        getSelfTestPeople({ orgCode })
          .then((res) => {
            let { data } = res;
            let selectList = data?.result || [];
            let sList = [];
            selectList.forEach((v) => {
              sList.push({
                dicValue: v.approveUserId,
                dicDesc: v.approveUser,
              });
            });
            this.selfPeopleSelect = sList;
            resolve();
          })
          .catch((_) => {
            this.selfPeopleSelect = [];
            reject();
          });
      });
    },
    //初始化页面
    initPage() {
      try {
        this.pageLoading = true;
        let records = JSON.parse(sessionStorage.getItem("record_ids"));
        this.activeKey = records.map((item) => item.id);
        this.basicData = records;
        let queue = this.basicData.map((v, i) => {
          this.$set(v, "loaded", true);
          this.$set(v, "operateMode", "editor");
          return this.getInspectionInit(v);
        });
        Promise.all(queue).then((_) => {
          this.getDetails().finally((_) => {
            this.pageLoading = false;
          });
        });
      } catch (error) {
        this.basicData = [];
        return new Error(error);
      }
    },

    //查询详情
    getDetails() {
      let { id } = this.$route.query;
      return new Promise((resolve, reject) => {
        bYJLDetails({ id })
          .then((res) => {
            let { data } = res;
            this.resultData = data?.result || {};
            //顶部流程条
            let flowList = data.result?.applyNodes || [];
            //处理记录
            let recordList = data?.result?.approveRecords || [];
            this.approveKey = recordList.map((item) => item.id);
            //报验信息
            let list = data?.result?.scheduleWbsProcedureList || [];

            //顶部流程条
            if (flowList.length > 0) {
              flowList.forEach((v, i) => {
                let { nodeDesc, operation } = v;
                v.subTitle = nodeDesc;
                if (operation == "0" || operation == "2") {
                  v.$$nodeStatus = "active";
                }
              });
            }
            this.flowSource = flowList;

            //处理记录
            recordList = recordList.filter((item) => item.operation != "1");
            recordList.forEach((v) => {
              let { formdetails } = v;
              this.$set(v, "formList", formdetails || []);
            });
            recordList.forEach((v) => {
              let { formList } = v;
              formList.forEach((item) => {
                if (item.elementType == "7") {
                  try {
                    let s = JSON.parse(item.selectDatas);
                    item.selectDatas = s;

                    let label = item.selectDatas.find(
                      (findItem) => findItem.value == item.elementValue
                    ).label;

                    item.elementValue = label || "";
                  } catch (error) {
                    item.selectDatas = [];
                  }
                }
              });
            });
            this.record = recordList;

            //报验信息
            list.forEach((v, i) => {
              let { formdetails, hierarchy, rangeValue } = v;

              this.basicData[i].formList.forEach((form) => {
                let { key, defalutValue } = form;

                if (key == "procedureItem") {
                  this.$set(this.basicData[i], "procedureItem", defalutValue);
                }

                //层级
                if (key == "cengji") {
                  this.$set(form, "defalutValue", Number(hierarchy));
                }
                //幅别
                if (key == "rangeValue") {
                  this.$set(form, "defalutValue", Number(rangeValue));
                }

                //是否合格
                if (key == "result") {
                  this.$set(form, "defalutValue", v.result + "");
                }
                //自检人
                if (key == "selfCheckPerson") {
                  this.$set(form, "defalutValue", v.selfCheckPerson);
                }

                //施工部位
                if (key == "sjsgbw") {
                  let keys = [
                    "positionKey1",
                    "positionKey2",
                    "positionKey3",
                    "positionKey4",
                    "positionKey5",
                    "positionKey6",
                  ];
                  keys.forEach((sgbw) => {
                    this.$set(
                      form,
                      sgbw,
                      v[sgbw] == null ? undefined : Number(v[sgbw])
                    );
                  });
                }
              });
              formdetails.forEach((item) => {
                let { elementKey, elementType, elementValue, fileList } = item;
                let currentForm = this.basicData[i].formList.find(
                  (v) => v.key == elementKey
                );
                //文本框
                if (elementType == "1" || elementType == "2") {
                  this.$set(currentForm, "defalutValue", elementValue);
                }

                //附件
                if (
                  elementType == "3" ||
                  elementType == "4" ||
                  elementType == "5"
                ) {
                  this.$set(currentForm, "defalutValue", fileList || []);
                }

                //位置
                if (elementType == "6") {
                  this.$set(currentForm, "defalutValue", elementValue);
                }
              });
            });

            resolve();
          })
          .catch((_) => {
            reject();
          })
          .finally((_) => {});
      });
    },

    getInspectionInit(item) {
      let { id } = item;
      return new Promise((resolve, reject) => {
        getInspectionInit(id, {})
          .then((res) => {
            let { data } = res;
            let source = data?.result || {};
            //处理 附件、图片、视频 类型的默认值
            (source?.wWorkflowForms || []).forEach((v) => {
              let { elementType, defalutValue } = v;
              if (
                elementType == "3" ||
                elementType == "4" ||
                elementType == "5"
              ) {
                if (!Array.isArray(defalutValue)) {
                  if (defalutValue) {
                    v.defalutValue = defalutValue.split(",");
                  } else {
                    v.defalutValue = [];
                  }
                }
              }
              v.disabled = 1;
            });
            this.$set(item, "formList", [
              ...this.buildDefaultForm(source || {}, "editor"),
              ...(source?.wWorkflowForms || []),
            ]);

            resolve();
          })
          .catch((_) => {
            reject();
          });
      });
    },

    //构件默认表单数据
    buildDefaultForm(item = {}, mode = "editor") {
      let routeQuery = this.$route.query;
      let {
        divisionalWorks,
        subDivisionalWorks,
        itemWorks,
        subItemWorks,
        procedureItem,
        orgCode,
        unitWorks,
        orgName,
      } = item?.scheduleWbs || {};
      let { cengjiShow, cengjiSelect, sjsgbwShow, rangeSelect, sjsgbwSelect } =
        item;
      let dynamicKeys = [
        "subDivisionalWorks",
        "itemWorks",
        "subItemWorks",
        "procedureItem",
      ];
      let forms = [
        {
          elementName: "标段名称",
          key: "orgName",
          disabled: 1,
          elementType: "1",
          defalutValue:
            routeQuery.inspectionStatus == 0 ? routeQuery.orgName : orgName,
          elementRequired: "0",
          orgCode,
          loading: false,
          $$formType: 0,
          selectDatas: [],
        },
        {
          elementName: "单位工程",
          key: "unitWorks",
          disabled: 1,
          elementType: "1",
          defalutValue:
            routeQuery.inspectionStatus == 0 ? routeQuery.unitWorks : unitWorks,
          elementRequired: "0",
          loading: false,
          $$formType: 0,
          selectDatas: [],
        },
        {
          elementName: "分部工程",
          key: "divisionalWorks",
          disabled: 1,
          elementType: "select",
          defalutValue: mode == "editor" ? divisionalWorks : undefined,
          elementRequired: "0",
          loading: false,
          $$formType: 0,
          selectDatas: [],
        },
        {
          elementName: "分部子工程",
          key: "subDivisionalWorks",
          disabled: 1,
          elementType: "select",
          defalutValue: mode == "editor" ? subDivisionalWorks : undefined,
          elementRequired: "0",
          loading: false,
          $$formType: 0,
          selectDatas: [],
        },
        {
          elementName: "分项工程",
          key: "itemWorks",
          disabled: 1,
          elementType: "select",
          defalutValue: mode == "editor" ? itemWorks : undefined,
          elementRequired: "0",
          loading: false,
          $$formType: 0,
          selectDatas: [],
        },
        {
          elementName: "子分项工程",
          key: "subItemWorks",
          disabled: 1,
          elementType: "select",
          defalutValue: mode == "editor" ? subItemWorks : undefined,
          elementRequired: "0",
          loading: false,
          $$formType: 0,
          selectDatas: [],
        },
        {
          elementName: "工序",
          key: "procedureItem",
          disabled: 1,
          elementType: "select",
          defalutValue: mode == "editor" ? procedureItem : undefined,
          elementRequired: "0",
          loading: false,
          $$formType: 0,
          selectDatas: [],
        },
        {
          elementName: "施工部位",
          key: "sjsgbw",
          disabled: 1,
          elementType: "sgbw",
          defalutValue: undefined,
          elementRequired: "0",
          selectDatas: sjsgbwSelect || [],
          loading: false,
          $$formType: 0,
          positionKey1: undefined,
          positionKey2: undefined,
          positionKey3: undefined,
          positionKey4: undefined,
          positionKey5: undefined,
          positionKey6: undefined,
        },
        {
          elementName: "幅别",
          key: "rangeValue",
          disabled: 1,
          elementType: "select",
          defalutValue: undefined,
          elementRequired: "0",
          selectDatas: rangeSelect || [],
          loading: false,
          $$formType: 0,
        },
        {
          elementName: "是否合格",
          key: "result",
          disabled: 1,
          elementType: "radio",
          defalutValue: "0",
          elementRequired: "0",
          selectDatas: [],
          loading: false,
          $$formType: 0,
        },
        {
          elementName: "自检人",
          key: "selfCheckPerson",
          disabled: 1,
          elementType: "zjr",
          defalutValue: undefined,
          elementRequired: "0",
          selectDatas: this.selfPeopleSelect || [],
          loading: false,
          $$formType: 0,
        },
        {
          elementName: "层级",
          key: "cengji",
          disabled: 1,
          elementType: "select",
          defalutValue: undefined,
          elementRequired: "0",
          selectDatas: cengjiSelect || [],
          loading: false,
          $$formType: 0,
        },
      ];

      //是否展示层级
      if (!cengjiShow) {
        forms = forms.filter((v) => v.key != "cengji");
      }

      //是否展示施工部位
      if (!sjsgbwShow) {
        forms = forms.filter((v) => v.key != "sjsgbw");
      }

      if (mode == "editor") {
        forms = forms.filter((v) => {
          let { key } = v;
          if (dynamicKeys.includes(key)) {
            if (item?.scheduleWbs[key]) {
              return v;
            }
          } else {
            return v;
          }
        });
      }

      return forms;
    },

    //下载附件
    download(file) {
      let { imagePath, realFileName } = file;
      downFileByUrl(imagePath, realFileName);
    },

    //附件预览
    viewFile(file) {
      let { id } = file;
      commonViewFile("beam", id);
    },

    //收起/更多
    putAwayMore(item) {
      if (this.approveKey.includes(item.id)) {
        this.approveKey = this.approveKey.filter((v) => v != item.id);
      } else {
        this.approveKey.push(item.id);
      }
    },

    //返回
    gotoBack() {
      let { orgCode, unitWorks, backPath } = this.$route.query;
      this.$router.push({
        path: backPath,
        query: {
          orgCode,
          unitWorks,
        },
      });
    },

    //校验状态名称
    fliterName(row) {
      let { operation } = row;
      switch (operation) {
        case "0":
          return "提交";

        case "1":
          return "处理中";

        case "2":
          return "通过";

        case "3":
          return "拒绝";

        case "4":
          return "驳回";

        case "9":
          return "待提交";

        default:
          return "--";
      }
    },

    //校验状态className
    checkStatusClass(row) {
      let { operation } = row;
      switch (operation) {
        case "0":
          return "submit";

        case "1":
          return "lock";

        case "2":
          return "normal";

        case "3":
          return "reject";

        case "4":
          return "reject";

        case "9":
          return "cancel";

        default:
          return "cancel";
      }
    },
  },
  destroyed() {
    sessionStorage.removeItem("record_ids");
  },
};
</script>

<style lang="less" scoped>
.inspection-details-container {
  box-sizing: border-box;
  height: 100%;
  padding: 10px 0px 10px 10px;
  .flex();
  flex-direction: column;
  /deep/.processes-card-warp {
    border: none;
  }
  .header {
    padding: 11px 20px;
    background-color: #fff;
    box-sizing: border-box;
    .flex();
    justify-content: space-between;
    align-items: center;
    border-bottom: 1px solid #f3f4f6;
    &::before {
      content: attr(header);
      height: 18px;
      border-left: 3px solid var(--primary-color);
      padding-left: 10px;
      font-size: 18px;
      font-family: Microsoft YaHei;
      font-weight: 400;
      color: #525a5d;
      line-height: 18px;
    }
    .back-button {
      color: var(--primary-color);
      background: #f1f2f7 !important;
      border: none;
    }
  }
  .main {
    background-color: #fff;
    flex: 1;
    height: 100%;
    .custom-scrollbar();
    .flex();
    flex-direction: column;
    .title {
      padding: 20px 0 0px 30px;
      font-size: 16px;
      font-family: Microsoft YaHei;
      font-weight: 400;
      color: #525a5d;
    }

    .cust-collapse-header {
      padding-left: 20px;
      flex: 1;
      .flex();
      align-items: center;
      font-size: 14px;
      color: var(--primary-color);
      font-family: Microsoft YaHei;
      font-weight: 400;
      > div {
        margin-right: 10px;
        .flow {
          display: inline-block;
          min-width: 60px;
          border-radius: 4px;
          text-align: center;
          font-size: 14px;
          font-family: Microsoft YaHei;
          font-weight: 400;
          color: #ffffff;
          &.normal {
            background: #4bc964;
          }
          &.lock {
            background: #ff993f;
          }
          &.reject {
            background: #ff3f4a;
          }
          &.submit {
            background: #0098ff;
          }
          &.cancel {
            background: #f1f2f7;
            color: #aab0bc;
          }
        }
      }
    }

    //处理记录
    .approve-record-container {
      box-sizing: border-box;
      padding: 20px 60px 30px 60px;
      overflow: hidden;
      font-family: Microsoft YaHei;
      .item {
        .flex();
        .time-date {
          flex-shrink: 0;
          min-width: 100px;
          font-size: 14px;
          color: #333333;
          line-height: 22px;
        }
        .link-line {
          .flex();
          flex-direction: column;
          margin: 4px 10px 0 10px;
          .content {
            flex: 1;
            .flex();
            flex-direction: column;
            align-items: center;
            .dots {
              width: 13px;
              height: 13px;
              border-radius: 50%;
              background-color: #fff;
              border: 2px solid #d9dce2;
              .flex();
              flex-direction: column;
              justify-content: center;
              align-items: center;
            }
            .lines {
              width: 1px;
              flex: 1;
              min-height: 50px;
              background-color: #d9dce2;
              margin-top: 3px;
            }
          }
        }
        .approve-container {
          flex: 1;
          .approve-user {
            margin-bottom: 10px;
            .flex();
            align-items: center;
            .name {
              font-size: 16px;
              color: #333333;
              margin-right: 10px;
            }
            .result {
              font-size: 14px;
              color: #666666;
            }
          }
          .approve-content {
            margin-bottom: 10px;
            font-weight: 400;
            font-size: 14px;
            color: #333333;
            padding: 6px 10px;
            border-radius: 4px;
            background: #f7f7f7;
            word-break: break-all;
          }

          .slide-fade-enter-active {
            transition: all 0.2s ease;
          }
          .slide-fade-leave-active {
            transition: all 0.1s ease;
          }
          .slide-fade-enter,
          .slide-fade-leave-to {
            transform: translateY(10px);
            opacity: 0;
          }

          .approve-extra {
            cursor: pointer;
            margin-bottom: 50px;
            font-size: 14px;
            font-weight: 400;
            color: var(--primary-color);
            .flex();
            align-items: center;
            .icon {
              transform: scale(0.75);
              margin-left: 4px;
              transition: 0.3s;
              &.active {
                transform: scale(0.75) rotate(180deg);
              }
            }
          }

          .approve-collapse {
            .flex();
            box-sizing: border-box;
            padding: 20px 0 0 10px;
            margin-bottom: 10px;
            background: #f7f7f7;
            border-radius: 4px;
            overflow: hidden;
            .name {
              font-weight: 400;
              flex-shrink: 0;
              font-size: 14px;
              color: #333333;
              padding-bottom: 20px;
            }
            .content {
              flex: 1;
              .custom-scrollbar();
              .text-container {
                margin: 0 0 20px 0;
                word-break: break-all;
              }
              /deep/.bj-upload-file {
                width: 100%;
                .choosed-file-warp {
                  padding: 0;
                  background-color: unset;
                  width: 100%;
                  height: 100%;
                  box-sizing: border-box;
                  margin: 0;
                  border-radius: 0;
                  border: none;
                  .file-list {
                    padding-left: 0;
                  }
                }
              }
            }
          }
        }
        &:last-child {
          .approve-extra {
            margin-bottom: 0;
          }
        }
      }
    }
  }
}
</style>
